<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Happy dong
 * Created Time: 2019-11-23 09:48
 *
 * Version: 2.0
 */

namespace App\Modules\Coupon\Repositories;


use App\Exceptions\NotFoundException;
use App\Models\CouponSend;
use Flower\Core\Repository\Eloquent\BaseRepository;

class CouponSendRepository extends BaseRepository
{
	public function model()
	{
		return CouponSend::class;
	}

	public function isExisted($id){
		$info = $this->find($id);
		if(empty($info)){
			throw  new NotFoundException(['msg'=>'优惠券不存在！']);
		}
		return $info;
	}
	public function add($userId, $request)
	{
		$data = [
			'store_id'  => $request->store_id,
			'coupon_id' => $request->coupon_id,
			'user_id'   => $userId,
			'createnum' => $request->createnum,
			'status'    => 1,
			'back_num'  => 0,
			'live_id'   => $request->live_id
		];
		return  $this->create($data);
	}

	/**
	 * 优惠券列表
	 * @param $userId
	 * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model[]
	 */
	public function getListByUserId($userId,$storeId){
		return $this->model->with('coupon:id,name,type,money,discount,use_condition,use_start_time,use_end_time')->select(['id','coupon_id','createnum'])->where(['user_id'=>$userId,'store_id'=>$storeId])->get();
	}


	/**
	 * 带回收的优惠列表
	 * @param $userId
	 * @param $storeId
	 * @return mixed
	 */
	public function getRemainListByUserIdStoreId($userId,$storeId){
		return $this->model->where(['user_id'=>$userId,'store_id'=>$storeId])->where('createnum','>','send_num')->get();
	}

	/**
	 * 跟新优惠券数据
	 * @param $sendId
	 * @return array
	 * @throws NotFoundException
	 */
	public function updateSendNums($sendId){
		$coupon = $this->isExisted($sendId);
		$remainNum = $coupon->createnum - $coupon->send_num - $coupon->back_num;
		if($remainNum){
			$coupon->send_num +=1;
			$coupon->save();
			return ['status'=>1,'data'=>$coupon->coupon_id];
		}
		return ['status'=>0,'data'=>$coupon->coupon_id];
	}


	public function isSendCoupon($userId,$storeId){
		$isSend = $this->model->with('coupon:id,name,type,money,discount,use_condition,use_start_time,use_end_time')->select(['id','coupon_id','createnum','send_num','back_num'])->where(['user_id'=>$userId,'store_id'=>$storeId])->where('created_at','>=',date('Y-m-d H:i:s',time()-config('constant.check_live_is_send_gift_time')))->orderBy('id','desc')->first();
		if(!empty($isSend)){
			$remainNum = $isSend->createnum - $isSend->send_num - $isSend->back_num;
			if(empty($remainNum)) $isSend = null;
		}
		return empty($isSend) ? [] : $isSend;
	}


}